package com.vogue.supplymall.order.domain.biz.impl;

import java.math.BigDecimal;

import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.order.domain.biz.OrderPayOfflineBiz;
import com.vogue.supplymall.order.domain.biz.OrderUpdateBiz;
import com.vogue.supplymall.order.domain.model.Order;
import com.vogue.supplymall.order.domain.model.OrderStatus;
import com.vogue.supplymall.order.domain.service.OrderService;
import com.vogue.supplymall.order.domain.service.OrderStatusService;
import com.vogue.supplymall.order.exception.OrderIsTimeOverException;
import com.vogue.supplymall.order.exception.UpdateOrderException;

/**
 * 线下支付业务处理Worker
 * @author cy
 */
@Service("orderPayOfflineBiz")
public class OrderPayOfflineBizImpl implements OrderPayOfflineBiz {

    public static final Logger LOGGER_ORDERPAYOFFLINEBIZIMPL = LoggerFactory.getLogger(OrderPayOfflineBizImpl.class);

    @Resource
    private OrderService orderService;
    @Resource
    private OrderStatusService orderStatusService;
    @Resource
    private OrderUpdateBiz orderUpdateBiz;
    @Autowired
    protected MessageSourceUtils messageSourceUtils;
    
    /**
     * 线下支付
     * @param orderid 订单id
     */
    public void orderPayOffline(Long orderid) {
        try {
            orderUpdateBiz.deleteAllPayment(orderid);
        } catch (Exception ex) {
            LOGGER_ORDERPAYOFFLINEBIZIMPL.error("订单编号[{}]保存新支付记录前清空旧支付记录失败，原因：{}", orderid, ex.getMessage());
            throw new UpdateOrderException(ex.getMessage());
        }
        Order order = orderService.get(orderid);
        orderUpdateBiz.saveOrderStateByShopWaitingOrder(orderPayOfflineTs(orderid, order.getFinalprice()));         
    }
    
    public OrderStatus orderPayOfflineTs(Long orderid, BigDecimal amount) {
        OrderStatus orderStatus = orderStatusService.selectOneByWhr("orderid=" + orderid);
        if (null == orderStatus) {
            throw new UpdateOrderException("订单状态记录为空");
        }
        /*必须是待付款状态*/
        if (orderStatus.getOrderstatus() != 0) {
            throw new UpdateOrderException("订单不是待支付状态");
        }

        /*判断时候超时*/
        long modifyTime = orderStatus.getModifyDate().getTime();
        long currentTime = System.currentTimeMillis();
        if ((currentTime - modifyTime) > ConstantBean.PAY_FAILURE_TIME) {
            throw new OrderIsTimeOverException(orderStatus.getOrderid().toString());
        }
        orderUpdateBiz.payOfflinePayment(orderid, amount);
        return orderStatus;
    }
}
